package com.huanghuang.shuadan.common.filter;

import com.alibaba.fastjson.JSON;
import com.huanghuang.shuadan.common.exception.user.UserException;
import com.huanghuang.shuadan.common.exception.user.UserExceptionEnum;
import com.huanghuang.shuadan.common.intercept.RequestWrapper;
import com.huanghuang.shuadan.service.entity.base.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.Writer;

/**
 * @author HH
 * @version 1.0
 * @date 2019/7/21 9:25
 * @description 描述
 */
@Slf4j
@WebFilter(filterName = "sessionFilter",urlPatterns = {"/user/*"})
public class SessionFilter implements Filter {

    String[] includeUrls = new String[]{"/user/login","/user/captcha","/user/register"};
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        HttpSession session = request.getSession(false);
        String uri = request.getRequestURI();
        boolean needFilter = isNeedFilter(uri);
        if (!needFilter) { //不需要过滤直接传给下一个过滤器
            filterChain.doFilter(servletRequest, servletResponse);
        }else { //需要过滤器
            // session中包含user对象,则是登录状态
            if(session!=null&&session.getAttribute("user") != null){
                log.info("登陆拦截 SessionFilter.doFilter:{}", session.getAttribute("user"));
                // System.out.println("user:"+session.getAttribute("user"));
                filterChain.doFilter(request, response);
            }else{
                response.setStatus(200);
                response.setContentType("text/JavaScript; charset=utf-8");
                Writer writer = response.getWriter();
                Result result = Result.error(new UserException(UserExceptionEnum.USER_NOT_LOGIN).getExceptionEnum());
                writer.append(JSON.toJSONString(result));
                writer.close();
            }
        }
    }

    public boolean isNeedFilter(String uri){
        for (String includeUrl : includeUrls) {
            if(includeUrl.equals(uri)) {
                return false;
            }
        }

        return true;
    }

    @Override
    public void destroy() {

    }
}
